package com.exp.base.util;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import javax.management.RuntimeErrorException;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.util.Assert;
import org.springframework.util.ResourceUtils;

import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;

public class SettingUtils {
	volatile private static Multimap<String,String> settingsMap = ArrayListMultimap.<String,String>create();
	static{
		try {
			refresh();
		} catch (IOException e) {
			throw new RuntimeErrorException(new Error(e));
		}
	}
	
	/**
	 * 刷新设置
	 * @throws IOException
	 */
	public static  synchronized void refresh() throws IOException {
		File cfgFile= ResourceUtils.getFile("classpath:settings.xml");
		Document doc = Jsoup.parse(cfgFile, "utf-8");
		Multimap<String,String> _settingsMap = ArrayListMultimap.<String,String>create();
		Element settingElement = doc.select("settings").get(0);
		for(Element element : settingElement.children()){
			collect(_settingsMap,element,"");
		};
		settingsMap = _settingsMap;
	}
	
	private static void collect(Multimap<String,String> map,Element element,String prefix){
		String nodeName = element.nodeName();
		if(StringUtils.isEmpty(prefix)){
			prefix = nodeName;
		}else{
			prefix += "."+nodeName;
		}
		Elements childs = element.children();
		if(childs.size()==0){
			String value = element.text();
			map.put(prefix, value);
		}else{
			for(Element child : childs){
				collect(map,child,prefix);
			};
		}
	}
	
	public static String getString(String key) throws Exception{
		Assert.notNull(key, "key 不能为空");
		Collection<String> col = settingsMap.get(key);
		if(col.isEmpty()){
			throw new Exception("找不到这个配置项");
		}else{
			return col.iterator().next();
		}
	}
	
	public static int getInt(String key) throws Exception{
		Assert.notNull(key, "key 不能为空");
		String value = getString(key);
		return NumberUtils.toInt(value);
	}
	
	public static String defaultString(String key,String defaultValue){
		Assert.notNull(key, "key 不能为空");
		try {
			String value = getString(key);
			return StringUtils.defaultIfBlank(value, defaultValue);
		} catch (Exception e) {
		}
		return defaultValue;
	}
	
	public static int defaultInt(String key,int defaultValue){
		Assert.notNull(key, "key 不能为空");
		try {
			int value = getInt(key);
			return value;
		} catch (Exception e) {
		}
		return defaultValue;
	}
	
	public static Collection<String> getStringArray(String key){
		Assert.notNull(key, "key 不能为空");
		Collection<String> col = settingsMap.get(key);
		return col;
	}
	
	
}
